<?php
/**
 * CopyGoodsToCloud.php class file.
 * @author wudg <544038230@qq.com>
 * @date 2020/12/27- 下午5:47
 */

namespace common\jobs\copy;


use common\constants\CopyConst;
use common\jobs\dao\PddCopyLogDao;
use common\jobs\dao\PddCopyProductsDao;
use common\exception\CopyException;
use common\components\api\isv\Goods;
use common\exception\ValidatorException;
use common\components\misc\ImportLogger;
use common\constants\CloudProductConst;
use common\exception\ServicesException;
use common\exception\JobException;
use common\helpers\AmountHelper;
use common\helpers\StringHelper;
use common\models\com\ComSpider;
use common\services\CloudProduct;
use console\components\helpers\ConsoleHelper;
use Littlesqx\AintQueue\JobInterface;
use Littlesqx\AintQueue\JobMiddlewareInterface;
use yii\base\Exception;
use yii\helpers\ArrayHelper;
use yii\helpers\FileHelper;
use common\models\es\EsCopyProducts;
use Yii;


/**
 * 队列上到云数据库
 * Class CopyGoodsToCloud
 * @package api\jobs\copy
 */
class CopyGoodsToCloud extends CopyBase implements \common\drivers\interfaces\JobInterface
{

    public $args = [];

    /**
     * @var ComSpider|null
     */
    public $sourceData;

    public function __construct($args)
    {
        $this->args = $args;
        $this->cacheSuccessKey .= $this->args['batch_id'];
        $this->cacheErrorKey .= $this->args['batch_id'];
        $this->totalCacheKey .= $this->args['batch_id'];

    }
    /**
     * 队列执行
     * @since 修复sku 没有图片时导致的错误
     * @inheritDoc
     */
    public function handle():void
    {
        try{
            $this->logger = new ImportLogger($this->_createFilePath());

            Yii::$app->db->open();
            $this->batchInfo = (new PddCopyLogDao())->getBatchInfoByPk($this->args['batch_id']);
            if(!$this->batchInfo)
            {
                throw new CopyException('批次号不存在');
            }

            $this->logInfo = (new PddCopyProductsDao())->getInfoByPk($this->args['log_id']);

            if(!$this->logInfo)
            {
                throw new CopyException('日志不存在');
            }

            //取消跳过
            if($this->logInfo->status == CopyConst::COPY_CANCEL){
                throw new JobException('任务已取消');
            }

            $spiderContent = ComSpider::findOne(['id'=>$this->args['spider_id']]);


            if(!$spiderContent)
            {
                throw new CopyException('复制源数据不存在');
            }
            $this->sourceData = $spiderContent;



            $this->_showLog('日志记录表ID: '.$this->logInfo->id.'，->> 采集记录表ID:'.$this->sourceData->id);

            $productMatchInfo = StringHelper::jsonDecode($this->sourceData->extend_data);
            /**
             * 默认库存为0
             */
            $stocks = 0;
            if(isset($productMatchInfo['skus']) && count($productMatchInfo['skus']))
            {
                $stocks = array_sum(ArrayHelper::map($productMatchInfo['skus'],'skuId','stock'));
            }
            $productData = [
                'title' => $productMatchInfo['title'],
                'cid' => $productMatchInfo['cid'] ?? 0,
                'num_iid' => $this->sourceData->plat_id,
                'store_id' => $this->args['store_id'], //仓库id
                'uid' => $this->args['uid'], //当前会员uid
                'mall_id' => $this->args['mall_id'], //当前店铺mall_id
                'stock' => $stocks,
                'copy_status' => CloudProductConst::COPY_NO,
                'platform' => $this->sourceData->platform,
                'prices' => $productMatchInfo['prices'],
                'status' => CloudProductConst::STATUS_YES,
                'main_pic' => $productMatchInfo['main_pic'],
                'mall_name' => $productMatchInfo['mall_name'],
                'out_mall_id' => $productMatchInfo['mall_id'],
            ];
            /**
             * 匹配下类目
             */
            $mappingCats = (new Goods())->pddGoodsOuterCatMappingGet([
                'outer_cat_id' => $productMatchInfo['cid'] ?? 0,
                'outer_cat_name' => '',
                'outer_goods_name' => $productMatchInfo['title'],
            ],$this->args['mall_id']);
            if(isset($mappingCats['cat_id3']) && $mappingCats['cat_id3'] != 0)
            {
                $productData['cid'] = $mappingCats['cat_id3'];
            }
            if(isset($mappingCats['cat_id4']) && $mappingCats['cat_id4'] != 0)
            {
                $productData['cid'] = $mappingCats['cat_id4'];
            }
            $productDetailData = [
                'sku_img' => StringHelper::jsonEncode($productMatchInfo['sku_img']),
                'pics' => StringHelper::jsonEncode($productMatchInfo['pics']),
                'attr' => StringHelper::jsonEncode($productMatchInfo['attr']),
//                'video' => StringHelper::jsonEncode($productMatchInfo['video']),
                'extend_data' => StringHelper::jsonEncode($productMatchInfo['extend_data']),
                'pc_desc' => $productMatchInfo['pc_desc'],
                'm_desc' => $productMatchInfo['m_desc'],
            ];

            foreach($productMatchInfo['skus'] as $k => $sku)
            {
                $productMatchInfo['skus'][$k]['price'] = AmountHelper::yuanTofen($sku['price']);
                $productMatchInfo['skus'][$k]['sale_price'] = AmountHelper::yuanTofen($sku['sale_price']);
                $productMatchInfo['skus'][$k]['cover'] = $sku['cover'] ?? '';
                $productMatchInfo['skus'][$k]['updated_at'] = $productMatchInfo['skus'][$k]['created_at'] = time();
            }
            $productSkusData = $productMatchInfo['skus'];
            $res = array();
            if($productSkusData){
                $res = array();
                foreach ($productSkusData as $value) {
                    //查看有没有重复项
                    if(isset($res[$value['skuId']])){
                        unset($value['skuId']);  //有：销毁
                    }else{
                        $res[$value['skuId']] = $value;
                    }
                }
            }
            $skus = array();
            if($res){
                foreach($res as $k=>$v){
                    $skus[] = $v;
                }
            }
            $productInfo = (new CloudProduct())->addProduct($productData,$productDetailData,$skus);
            if($productInfo)
            {
                $this->setSuccessNum();
                $this->logInfo->title = $productInfo->title;
                $this->logInfo->copy_id = (string)$productInfo->id; //详情从云库中拿
                $this->logInfo->source_id = $spiderContent->id; //快照表id
                $this->logInfo->cid = $productInfo->cid;
                $this->logInfo->num_iid = $productInfo->num_iid;
                $this->logInfo->main_pic = $productInfo->main_pic;
                $this->logInfo->source_mall_name = $productInfo->mall_name;
                $this->logInfo->source_mall_id = $productInfo->mall_id;
                $this->logInfo->status = CopyConst::COPY_YES;
                $this->logInfo->save();
                //同步es
                //$info = $this->logInfo->toArray();
//                if($info){
//                    if(isset($info['id'])){
//                        $idsArr[] = $info['id'];
//                        $es = new EsCopyProducts();
//                        unset($info['id']);
//                        $es->updateByfield($idsArr,$info);
//                    }
//                }
                $this->_showLog('成功更新云库商品，采集表id:'.$this->sourceData->id.'=>云库表id:'.$productInfo->id.'商品标题为:'.$productInfo->title);
                Yii::$app->db->close();
            }else{
                throw new CopyException('写入云库失败');
            }
        }catch (CopyException $e)
        {
            $this->_showLog('[流程相关]入云库数据异常->'.$e->getMessage());
            $this->setErrorNum();
            $this->logInfo->error_info = substr($e->getMessage(),0,240);
            $this->saveLog([
                'status' =>  CopyConst::COPY_FAILED,
                'product_status' =>  0
            ]);

        }catch (ServicesException $e)
        {
            $this->_showLog('[服务相关]入云库数据异常->'.$e->getMessage());
            $this->setErrorNum();
            $this->logInfo->error_info = substr($e->getMessage(),0,240);
            $this->saveLog([
                'status' =>  CopyConst::COPY_FAILED,
                'product_status' =>  0
            ]);

        }catch (ValidatorException $e)
        {
            $this->_showLog('[验证异常]入云库数据异常->'.$e->getMessage());
            $this->setErrorNum();
            $this->logInfo->error_info = substr($e->getMessage(),0,240);
            $this->saveLog([
                'status' =>  CopyConst::COPY_FAILED,
                'product_status' =>  0
            ]);
        }catch (Exception $e)
        {
            $this->setErrorNum();
            $this->_showLog($e->getMessage());
        }catch (JobException $e)
        {
            //$this->setErrorNum();
            $this->_showLog($e->getMessage());
        }finally {
            Yii::$app->db->close();
        }
    }



    /**
     * 采集log目录初始化
     * @return bool|string
     * @throws \yii\base\Exception
     */
    protected function _createFilePath()
    {
        $path = Yii::getAlias('@runtime/job/cloud/');

        if(!is_dir($path)) {
            FileHelper::createDirectory($path);
        }

        return $path;
    }


    private function _showLog($msg)
    {
        ConsoleHelper::runInfo($this->args['spider_id'].':cloud:'.$msg);
        $this->logger->add($this->args['spider_id'].':cloud:'.$msg);
    }


    /**
     * @inheritDoc
     */
    public function canRetry(int $attempt, $error): bool
    {
        return false;
    }

    /**
     * @inheritDoc
     */
    public function retryAfter(int $attempt): int
    {
        return 0;
    }

    /**
     * @inheritDoc
     */
    public function failed(int $id, array $payload): void
    {
        // TODO: Implement failed() method.
    }

    /**
     * @inheritDoc
     */
    public function middleware(): array
    {
        return [];
    }
}